package leetcode.code1425;

import java.util.Deque;
import java.util.LinkedList;
import java.util.PriorityQueue;

import leetcode.IDebug;
import leetcode.helper.H;

// 用单调栈，选择大数的贪心方式是错的。
public class Solution3 implements IDebug {

	public int constrainedSubsetSum(int[] nums, int k) {
		int ans = Integer.MIN_VALUE;
		PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> b[0] - a[0]);// 选择后的最大结果，对应位置
		for (int i = 0; i < nums.length; i++) {
			while (!queue.isEmpty() && queue.peek()[1] + k < i) {
				queue.poll();
			}
			int cur = nums[i];
			if (!queue.isEmpty()) {
				cur = Math.max(queue.peek()[0] + nums[i], cur);
			}
			queue.add(new int[] { cur, i });
			ans = Math.max(cur, ans);
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(23, this.constrainedSubsetSum(H.str2array3("[10,-2,-10,-5,20]"), 2));
		H.compare(125,
				this.constrainedSubsetSum(H.str2array3("[100,-10,-10,-10,-2,-2,-10,-100,15,-5,-10,10,2,-10,5,20]"), 2));
		H.compare(23, this.constrainedSubsetSum(H.str2array3("[10,-2,-10,-5,20]"), 2));
		H.compare(37, this.constrainedSubsetSum(H.str2array3("[10,2,-10,5,20]"), 2));
		H.compare(-1, this.constrainedSubsetSum(H.str2array3("[-1,-2,-3]"), 2));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution3 so = new Solution3();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
